package com.jcfk.eam.service.mould;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jcfk.common.business.service.BaseService;
import com.jcfk.common.core.utils.BeanUtils;
import com.jcfk.common.security.utils.SecurityUtils;
import com.jcfk.common.web.domain.DataPage;
import com.jcfk.common.web.domain.RetResult;
import com.jcfk.eam.dao.mould.MouldBomGroupDao;
import com.jcfk.eam.domain.dto.mould.MouldBomDetailDTO;
import com.jcfk.eam.domain.dto.mould.MouldBomGroupDTO;
import com.jcfk.eam.domain.po.mould.MouldBomDetail;
import com.jcfk.eam.domain.po.mould.MouldBomGroup;
import com.jcfk.eam.domain.query.mould.MouldBomGroupQuery;
import com.jcfk.eam.util.enums.CodeGeneratorEnu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.jcfk.common.core.utils.BeanUtils.convertList;

/**
 * 模具bom组合表
 *
 * @author yrl
 * @email 
 * @date 2024-11-08
 */
@Service
public class MouldBomGroupService extends BaseService<MouldBomGroupDao, MouldBomGroup> {


    @Autowired
    private MouldBomDetailService mouldBomDetailService;

    /**
     * ModBomGroup分页查询
     *
     * @param page  分页设置
     * @param query 查询条件
     * @return 分页查询结果
     */
    public DataPage<MouldBomGroupDTO> queryByPage(DataPage<MouldBomGroupDTO> page, MouldBomGroupQuery query) {
        // 分页查询
    query.setMaterialCode(StringUtils.isEmpty(query.getMaterialCode()) ? query.getMaterialCode() : query.getMaterialCode() + "%");
    query.setMaterialName(StringUtils.isEmpty(query.getMaterialName()) ? query.getMaterialName() : query.getMaterialName() + "%");
        page = this.baseMapper.queryByPage(page, query);
        return page;
    }

    /**
     * 根据条件获取单表信息列表
     *
     * @param query 查询条件
     * @return List<ModBomGroupDTO>
     */
    public List<MouldBomGroupDTO> getList(MouldBomGroupQuery query) {
        // 查询条件
        QueryWrapper<MouldBomGroup> qw = new QueryWrapper<>();
        qw.lambda().eq(!StrUtil.isEmpty(query.getEnabled()), MouldBomGroup::getEnabled, query.getEnabled());
        qw.lambda().eq(!StrUtil.isEmpty(query.getDeleted()), MouldBomGroup::getDeleted, query.getDeleted());
        qw.lambda().like(!StrUtil.isEmpty(query.getMaterialCode()), MouldBomGroup::getMaterialCode, query.getMaterialCode());
        qw.lambda().like(!StrUtil.isEmpty(query.getMaterialName()), MouldBomGroup::getMaterialName, query.getMaterialName());
        // 查询数据
        List<MouldBomGroup> list = super.list(qw);

        return convertList(list, MouldBomGroupDTO.class);
    }

    /**
     * 获取根据关联id详情表列表
     * @param query 查询条件
     * @return List<ModBomGroupDTO>
     */
    public List<MouldBomDetailDTO> getDetails(MouldBomGroupQuery query) {
        // 查询条件
        QueryWrapper<MouldBomDetail> qw = new QueryWrapper<>();
        qw.lambda().eq(!StrUtil.isEmpty(query.getId()), MouldBomDetail::getBomId, query.getId());
        qw.lambda().eq(MouldBomDetail::getDeleted, "0");

        // 查询数据
        List<MouldBomDetail> list = mouldBomDetailService.list(qw);

        return convertList(list, MouldBomDetailDTO.class);
    }



    /**
     * 判断ModBomGroup是已经存在
     *
     * @param dto
     * @return
     */
    public RetResult<String> isValid(MouldBomGroupDTO dto) {
        QueryWrapper<MouldBomGroup> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", 0);
                                                                    queryWrapper.eq("bom_code", dto.getBomCode());
        if (!StringUtils.isEmpty(dto.getId())) queryWrapper.ne("id", dto.getId());
        int count = this.count(queryWrapper);

        if (count > 0) return RetResult.fail("bom编号已存在");
        QueryWrapper<MouldBomGroup> uniqueQuery = new QueryWrapper<>();
        uniqueQuery.eq("deleted", 0);
        uniqueQuery.eq("equip_id", dto.getEquipId());
        uniqueQuery.eq("process_id", dto.getProcessId());
        uniqueQuery.eq("project_id", dto.getProjectId());
        uniqueQuery.eq("material_id", dto.getMaterialId());
        if (!StringUtils.isEmpty(dto.getId())) uniqueQuery.ne("id", dto.getId());
        int uniqueCount = this.count(uniqueQuery);

        if (uniqueCount > 0) return RetResult.fail("一个物料在同一生产线,工序,设备下已存在BOM");
        return RetResult.ok();
    }

    /**
     * 插入模具bom组合表
     *
     * @param dto 插入对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void insert(MouldBomGroupDTO dto) {

        // 保存
        MouldBomGroup item = new MouldBomGroup();
        BeanUtils.copyProperties(dto, item);
        item.setBomCode(CodeGeneratorEnu.BOM_CODE.build());
        this.setDefaultValue(item);

        super.save(item);

        // 保存明细表
        mouldBomDetailService.saveBatch(dto.getDetails(),item.getId());
    }


    /**
     * 更新模具bom组合表
     *
     * @param dto 更新对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void update(MouldBomGroupDTO dto) {

        // 保存
        MouldBomGroup item = new MouldBomGroup();
        BeanUtils.copyProperties(dto, item);

        // 默认数据
        this.setDefaultValue(item);

        super.updateById(item);

        // 设置关联主键
        for (MouldBomDetailDTO detail : dto.getDetails()) {
            detail.setBomId(item.getId());
        }
        // 保存明细表
        mouldBomDetailService.saveBatch(dto.getDetails(),item.getId());
    }



        /**
         * 根据批量主键删除模具bom组合表(逻辑删除)
         *
         * @param dto
         * @return bool
         */
        @Transactional(rollbackFor = Exception.class)
        public Boolean logicDeleteList(MouldBomGroupDTO dto) {

            MouldBomDetail mouldBomDetail = new MouldBomDetail();
            mouldBomDetail.setLastUpdatedUserId(SecurityUtils.getUserId());
            mouldBomDetail.setLastUpdateTime(new Date());
            mouldBomDetail.setLastUpdatedUserName(SecurityUtils.getUserName());
            mouldBomDetail.setDeleted("1");
            mouldBomDetailService.update(mouldBomDetail,Wrappers.<MouldBomDetail>lambdaQuery()
                    .in(MouldBomDetail::getBomId,dto.getIds()));

            MouldBomGroup item = new MouldBomGroup();

            item.setLastUpdatedUserId(SecurityUtils.getUserId());
            item.setLastUpdateTime(new Date());
            item.setLastUpdatedUserName(SecurityUtils.getUserName());
            item.setDeleted("1");
            
            QueryWrapper<MouldBomGroup> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("id", dto.getIds());

            return this.update(item, queryWrapper);
        }

    /**
     * 设置添加默认值
     *
     * @param item 添加对象
     */
    public void setDefaultValue(MouldBomGroup item) {
        if (StrUtil.isEmpty(item.getCreatedUserId())) {
            item.setCreatedUserId(SecurityUtils.getUserId());
            item.setCreateTime(new Date());
                item.setDeleted("0");
                item.setEnabled("1");
                                                                                        item.setCreatedUserName(SecurityUtils.getUserName());
                                                                                                                                                                                                                    }
        item.setLastUpdatedUserId(SecurityUtils.getUserId());
        item.setLastUpdateTime(new Date());

                                        item.setLastUpdatedUserName(SecurityUtils.getUserName());
                                                                }


    /**
     * 根据主键获取模具bom组合表信息
     *
     * @param id 主键
     * @return StandardCodeDTO
     */
    public MouldBomGroupDTO get(String id) {
        // 查询数据
        MouldBomGroup item = this.baseMapper.selectById(id);
        Assert.notNull(item, "BOM数据不存在");
            MouldBomGroupDTO dto = new MouldBomGroupDTO();
        try {
            BeanUtils.copyProperties(item, dto);
            MouldBomGroupQuery mouldBomGroupQuery = new MouldBomGroupQuery();
            mouldBomGroupQuery.setId(id);
            List<MouldBomDetailDTO> details = this.getDetails(mouldBomGroupQuery);
            List<MouldBomDetailDTO> mouldBomDetailDTOS = convertListToTree(details,"0");
            dto.setDetails(mouldBomDetailDTOS);
        } catch (RuntimeException e) {
            throw e;
        }

        return dto;
    }
    public List<MouldBomDetailDTO> convertListToTree(List<MouldBomDetailDTO> details, String parentId) {
        return details.stream().filter(detail -> detail.getParentId().equals(parentId))
                .sorted(Comparator.comparing(MouldBomDetailDTO::getSort))
                // 递归构建子节点
                .peek(detail -> detail.setDetails(convertListToTree(details.stream()
                                .filter(d -> d.getParentId().equals(detail.getId()))
                                .collect(Collectors.toList()),
                        detail.getId()))
                ).collect(Collectors.toList());
    }


    /**
     * 根据主键获取模具bom组合表信息
     *
     * @param id 主键
     * @return StandardCodeDTO
     */
    @Transactional
    public void deleteItem(String id) {
        MouldBomGroup item = getById(id);
        Assert.notNull(item, "BOM数据不存在");
        this.setDefaultValue(item);
        item.setDeleted("1");

        this.updateById(item);
        // 更新子表删除字段

        MouldBomDetail mouldBomDetail = new MouldBomDetail();
        mouldBomDetail.setLastUpdatedUserId(SecurityUtils.getUserId());
        mouldBomDetail.setLastUpdateTime(new Date());
        mouldBomDetail.setLastUpdatedUserName(SecurityUtils.getUserName());
        mouldBomDetail.setDeleted("1");
        mouldBomDetailService.update(mouldBomDetail,Wrappers.<MouldBomDetail>lambdaQuery()
                .eq(MouldBomDetail::getBomId,item.getId()));
    }



    public MouldBomGroupDTO queryDetailTreeCopyByNum(String bomCode) {
        Assert.notEmpty(bomCode, "bom编号不能为空");

        // 查询条件
        QueryWrapper<MouldBomGroup> qw = new QueryWrapper<>();
        qw.lambda().eq(MouldBomGroup::getBomCode, bomCode);

        // 查询数据
        MouldBomGroup bomGroup = this.getOne(qw);
        Assert.notNull(bomGroup, "BOM数据不存在");
        MouldBomGroupDTO item = new MouldBomGroupDTO();
        BeanUtils.copyProperties(bomGroup, item);
        item.setDetails(mouldBomDetailService.queryTreeCopyByNum(bomGroup.getId()));
        return item;
    }

    /**
     * 批量停用模具bom主表数据
     */
    @Transactional
    public void disabledList(MouldBomGroupDTO mouldBomGroupDTO) {
        List<MouldBomGroup> list = this.list(Wrappers.<MouldBomGroup>lambdaQuery()
                .in(MouldBomGroup::getId, mouldBomGroupDTO.getIds()));
        List<MouldBomGroup> deactivated = list.stream().filter(t -> t.getEnabled().equals("0")).collect(Collectors.toList());
        Assert.isTrue(CollUtil.isEmpty(deactivated), "BOM数据:{},已停用",
                deactivated.stream().map(MouldBomGroup::getBomCode).collect(Collectors.joining(",")));
        MouldBomGroup item = new MouldBomGroup();

        this.setDefaultValue(item);
        item.setEnabled("0");
        QueryWrapper<MouldBomGroup> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", mouldBomGroupDTO.getIds());

        this.update(item, queryWrapper);

    }
}

